<?php

declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\Model;
use think\facade\Db;
use think\facade\Validate;

class Substation extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        'login',
        'auth'
    ];

    /**
     * 推荐位模型
     * @var \app\admin\model\Substation
     */
    protected $model;

    /**
     * 允许批量修改的字段
     * @var array
     */
    protected $allowFields = ['status','weigh','new_window'];

    /**
     * 初始化操作
     */
    public function initialize()
    {
        parent::initialize();

        $this->model = new \app\admin\model\Substation();
    }

    public function index()
    {
        $id=$this->request->param('id');
        if(!$id||$id<0)
        {
            $parent_id="-1";
            $backid="-1";
            $backname="";
        }
        else
        {
            $Info = $this->model->where(['id'=>$id])->find();
            $parent_id=$id;
            $backid=$Info['parent_id'];
            $backname=$Info['name'];
           
        }
		
		if ($this->request->isAjax()) {
           
            if ($this->request->param('searchTable')) {
                return $this->selectPage(); // 判断请求。如果是动态下拉组件请求，则交接给selectPage方法
            }
			$lang = $this->request->param('clang', $this->contentLang);
            list($map, $limit, $offset, $order, $sort) = $this->buildparams();
			//$data = $this->model->where($map)->where(['lang'=>$lang,'parent_id'=>$parent_id])->order(['weigh'=>'desc','id'=>'asc'])->limit($offset, $limit)->select();
            $data = $this->model->where($map)->where(['lang'=>$lang,'parent_id'=>$parent_id])->order($sort, $order)->limit($offset, $limit)->select();
            $total = $this->model->where($map)->where(['lang'=>$lang,'parent_id'=>$parent_id])->order($sort, $order)->count();
 
            return json(['total'=>$total,'rows'=>$data]);
        }
        
        $this->view->assign('parent_id',$parent_id);
        $this->view->assign('backid',$backid);
        $this->view->assign('backname',$backname);
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed|string|void
     */
    public function add()
    {
        $id=$this->request->param('id');
        $this->view->assign('parent_id',$id);
        if ($this->request->isPost()) {
            $row = $this->request->param('row/a','',null);
            $admin_id = $this->user->id;

            $data = [
                'admin_id' => $admin_id,
                'parent_id' => $row['parent_id'],
				'name' => $row['name'],
				//'image' => $row['image'],
                'math' => $row['math'],
				'seotitle' => $row['seotitle'],
				'keywords' => $row['keywords'],
				'description' => $row['description']
            ];

            // 判断唯一
            $tmpId = \app\admin\model\Substation::where(['math'=>$row['math'],'lang'=>$this->contentLang])->value('id');
            if ($tmpId) {
                $this->error(lang('%s,existed',[$row['math']]));
            }
			
			$data['lang'] = $this->contentLang;
            Db::startTrans();
            try {
                $result = $this->model->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
				$this->cache->clear();
				$this->success();
            } else {
				$this->error(lang('No rows added'));
            }
			$this->error(lang('No rows added'));
        }
		
		return $this->view->fetch();
    }

    /**
     * 修改
     * @param null $id
     */
    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(lang('Record does not exist'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a",'',null);
            if ($params) {
                $admin_id = $this->user->id;
                $data = [
                    'admin_id' => $admin_id,
                    'parent_id' => $params['parent_id'],
					'name' => $params['name'],
					//'image' => $params['image'],
                    'math' => $params['math'],
					'seotitle' => $params['seotitle'],
					'keywords' => $params['keywords'],
					'description' => $params['description']
                ];
                //if (Db::name('substation')->where(['math'=>$data['math'],'lang'=>$row['lang']])->where('id','<>', $row['id'])->value('id')) {
                //    //$this->error(lang('Substation already exists'));
                 //   $this->error(lang('%s,existed',[$data['math']]));
                //}
				
				$result = false;
                Db::startTrans();
                try {
                    $result = $row->save($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                if ($result !== false) {
                    $this->cache->clear();
                    $this->success();
                } else {
                    $this->error(lang('Unmodified record'));
                }
            }
            $this->error(lang('Parameter is empty'));
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
        //return $this->view->fetch('', compact('row'));
    }
}